package com.gitee.xzb617.mybatis.batch;

import com.gitee.xzb617.mybatis.batch.util.ReflectUtil;
import org.apache.commons.collections4.ListUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import tk.mybatis.mapper.common.BaseMapper;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.List;

public class BatchMapper {

    /**
     * 这是局部开启了局部批量模式 ExecutorType = Batch, 批次进行 commit, 以此提高批量插入/更新的速度。
     * 开启批量插入模式，对应的局部批量方法无法返回数据表中受影响的行数
     * 【注意】：应根据自己引入的通用Mapper替换
     */

    @Resource
    private DefaultSqlSessionFactory sqlSessionFactory;

    /**
     * 批量新增
     * @param data 数据
     * @param mapperClazz Mapper对应类型
     * @param <T>
     */
    public <T> void insertBatch(List<T> data, Class<?> mapperClazz) {
        SqlSession batchSqlSession = null;
        try {
            batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            List<List<T>> logsList = ListUtils.partition(data, smartPartition(data));
            BaseMapper<T> baseMapper = getMapper(batchSqlSession, mapperClazz);
            for (int i = 0; i < logsList.size(); i++) {
                for (T row : logsList.get(i)) {
                    baseMapper.insertSelective(row);
                }
                batchSqlSession.commit();
            }
        } finally {
            if (batchSqlSession != null) {
                batchSqlSession.close();
            }
        }
    }

    /**
     * 批量更新
     * @param data 数据
     * @param mapperClazz Mapper对应的类型
     * @param <T>
     */
    public <T> void updateBatch(List<T> data, Class<?> mapperClazz) {
        SqlSession batchSqlSession = null;
        try {
            batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            List<List<T>> logsList = ListUtils.partition(data, smartPartition(data));
            BaseMapper<T> baseMapper = getMapper(batchSqlSession, mapperClazz);
            for (int i = 0; i < logsList.size(); i++) {
                for (T row : logsList.get(i)) {
                    baseMapper.updateByPrimaryKeySelective(row);
                }
                batchSqlSession.commit();
            }
        } finally {
            if (batchSqlSession != null) {
                batchSqlSession.close();
            }
        }
    }


    /**
     * 获取通用Mapper
     * @param sqlSession
     * @param mapperClazz
     * @return
     */
    private BaseMapper getMapper(SqlSession sqlSession, Class<?> mapperClazz) {
        return (BaseMapper) sqlSession.getMapper(mapperClazz);
    }

    /**
     * 智能解析分组数
     * @param data 数据
     * @param <T>
     * @return
     */
    private <T> int smartPartition(List<T> data) {
        // 获取参数类型的字段个数，根据字段数量来合理拆分
        T row = data.get(0);
        Class<?> aClass = row.getClass();
        List<Field> fields = ReflectUtil.getFields(aClass);
        int length = fields.size();
        int mod = (length / 50) + 1;
        return Math.max( 5000 - mod * 500, 2000);
    }

}
